//
//  PPRetrieveViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/18/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPRetrieveViewController.h"
#import "PPHomeViewController.h"
#import "PPHomeNavigationController.h"

#import "PPNetworkService.h"

#import "DGGlobalTimerTask.h"
#import "DGGlobalTimerManager.h"
#import "DGGlobalTimerObserver.h"
#import "DGGlobalTimerObserverManager.h"
#import "DGGlobalTimerTaskManager.h"

@interface PPRetrieveViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *phontField;
@property (weak, nonatomic) IBOutlet UITextField *codeField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (weak, nonatomic) IBOutlet UIButton *actionButton;

@property (readwrite, nonatomic, strong) UIButton *hiddenButton;
@property (readwrite, nonatomic, strong) UIButton *retrieveButton;
@property (readwrite, nonatomic, strong) UIView *bottomView;
@property (readwrite, nonatomic, assign) CGFloat keyboardTop;
@property (readwrite, nonatomic, strong) DGGlobalTimerObserver *timerObserver;
@end

@implementation PPRetrieveViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [[DGGlobalTimerObserverManager sharedInstance] removeGlobalTimerObserver:_timerObserver];
}

- (void)viewDidLoad {
    [super viewDidLoad];

//    _keyboardTop = self.view.height;
//   self.edgesForExtendedLayout = UIRectEdgeNone;;
    self.title = @"找回密码";
    
    [self setupBackItem];
    
    self.view.backgroundColor = [UIColor whiteColor];

    {
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        leftView.backgroundColor = [UIColor clearColor];
        _phontField.leftView = leftView;
        _phontField.leftViewMode = UITextFieldViewModeAlways;

        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        rightView.backgroundColor = [UIColor clearColor];
        _phontField.rightView = rightView;
        _phontField.rightViewMode = UITextFieldViewModeAlways;
    }

    {
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        leftView.backgroundColor = [UIColor clearColor];
        _codeField.leftView = leftView;
        _codeField.leftViewMode = UITextFieldViewModeAlways;

        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        rightView.backgroundColor = [UIColor clearColor];
        _codeField.rightView = rightView;
        _codeField.rightViewMode = UITextFieldViewModeAlways;
    }

    {
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        leftView.backgroundColor = [UIColor clearColor];
        _passwordField.leftView = leftView;
        _passwordField.leftViewMode = UITextFieldViewModeAlways;

        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 48, 46)];
        rightView.backgroundColor = [UIColor clearColor];
        _passwordField.rightView = rightView;
        _passwordField.rightViewMode = UITextFieldViewModeAlways;

        _hiddenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _hiddenButton.adjustsImageWhenHighlighted = NO;
        [_hiddenButton setImage:[UIImage imageNamed:@"code-off"] forState:UIControlStateNormal];
        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateHighlighted|UIControlStateSelected];
        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateSelected];
        [_hiddenButton sizeToFit];
        _hiddenButton.center = CGPointMake(rightView.width/2, rightView.height/2);
        [_hiddenButton addTarget:self action:@selector(hiddenButtonDidPressed:) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:_hiddenButton];
    }

    _bottomView = [[UIView alloc] init];
    _bottomView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_bottomView];

    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(retrieveButtonDidPressed)];
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    
//    _retrieveButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    _retrieveButton.enabled = NO;
//    [_retrieveButton setTitle:@"完成" forState:UIControlStateNormal];
//    [_retrieveButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xffdd17]] stretchableImageByCenter] forState:UIControlStateNormal];
//    [_retrieveButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf9d430]] stretchableImageByCenter] forState:UIControlStateHighlighted];
//    [_retrieveButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf2f2f2]] stretchableImageByCenter] forState:UIControlStateDisabled];
//    [_retrieveButton addTarget:self action:@selector(retrieveButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
//    [_bottomView addSubview:_retrieveButton];
    
    

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];


    __weak typeof(self)weakSelf = self;
    _timerObserver = [[DGGlobalTimerObserver alloc] init];
    _timerObserver.key = @"register_verify_code_timer";
    _timerObserver.identifier = @"retrieve_button";
    _timerObserver.initializedBlock = ^(NSTimeInterval remains){
        [weakSelf layoutActionButtonWithRemains:remains];
    };
    _timerObserver.triggeredBlock = ^(NSTimeInterval remains){
        [weakSelf layoutActionButtonWithRemains:remains];
    };
    _timerObserver.completedBlock = ^{
        [weakSelf layoutActionButtonWithRemains:0];
    };
    [[DGGlobalTimerObserverManager sharedInstance] addGlobalTimerObserver:_timerObserver];
}

- (void)didReceiveKeyboardWillChangeFrameNotification:(NSNotification *)notification {
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];

    CGRect rect = [[[UIApplication sharedApplication] keyWindow] convertRect:endRect toView:self.view];

    _keyboardTop = CGRectGetMinY(rect);

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|(curve << 16) animations:^{
        _bottomView.bottom = _keyboardTop;
    } completion:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _bottomView.frame = CGRectMake(0, _keyboardTop - 45, self.view.width, 45);

    _retrieveButton.frame = _bottomView.bounds;
}

- (void)layoutActionButtonWithRemains:(NSTimeInterval)remains {
    if(remains <= 0) {
        [_actionButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        _actionButton.enabled = YES;
    } else {
        [_actionButton setTitle:[NSString stringWithFormat:@"%li秒", (long)round(remains)] forState:UIControlStateNormal];
        _actionButton.enabled = NO;
    }
}

- (IBAction)actionButtonDidPressed:(UIButton *)sender {
    NSString *phoneString = _phontField.text;

    if([phoneString isValidPhoneNumber]) {

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

        __weak typeof(self)weakSelf = self;

        [PPNetworkService sendVerfyCodeWithPhoneNumber:phoneString type:2 callback:^(id data, NSError *error) {
            __strong typeof(weakSelf)strongSelf = weakSelf;

            if(strongSelf == nil) {
                return;
            }

            if(error == nil) {
                [hud hide:YES];

                [[DGGlobalTimerManager sharedInstance] rescheduleGlobalTimerForTaskKey:@"register_verify_code_timer" interval:1 duration:60];
            } else {
                [hud hide:YES];

                [strongSelf.navigationController.view toastMessage:error.networkPrompt];
            }
        }];

    } else {
        [self.navigationController.view toastMessage:@"请输入正确的手机号"];
    }
}

- (void)hiddenButtonDidPressed:(UIButton *)button {
    button.selected = !button.selected;

    _passwordField.secureTextEntry = !button.selected;
}

- (void)retrieveButtonDidPressed {

//    if(!_retrieveButton.enabled) {
//        return;
//    }

    NSString *phone = _phontField.text;
    NSString *code = _codeField.text;
    NSString *password = _passwordField.text;

    //去除空格符
    password = [password stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    //匹配正则表达式规则
    NSString *regex = @"^[\\w\\-\\_\u4e00-\u9fa5]{6,16}$";
    //    @"(^[\u4e00-\u9fa5]+$)"  @"^[\\w\\-\\_\u4e00-\u9fa5]{2,12}$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

    if (![emailTest evaluateWithObject:password])
    {
        [self.view toastMessage:@"密码长度要求在6-16位,且不能包含特殊字符" duration:1.f];
        return;
    }

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    NSNumber *genToken = DGCurrentAccount.credential.token.length == 0 ? @(1) : @(0);

    __weak typeof(self)weakSelf = self;
    [PPNetworkService verfyPhoneCodeWithPhoneNumber:phone genToken:genToken code:code callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {

            [PPNetworkService resetPasswordWithPhoneNumber:phone newPassword:password callback:^(id data, NSError *error) {
                __strong typeof(weakSelf)strongSelf = weakSelf;

                if(strongSelf == nil) {
                    return;
                }

                [hud hide:YES];

                if(error == nil) {

                    DGAccount *account = [[DGAccount alloc] init];
                    account.userID = [data validStringForKey:@"user"];
                    account.username = phone;
                    account.credential = [[DGAccountCredential alloc] init];
                    account.credential.userID = account.userID;
                    account.credential.token = [data validStringForKey:@"token"];

                    [[PPAccountManager sharedInstance] loginWithAccount:account completion:^(BOOL success) {

                        [strongSelf.navigationController.view toastMessage:@"密码修改成功" duration:2 completion:^{
                            if(success) {
                                PPHomeViewController *homeViewController = [[PPHomeViewController alloc] init];
                                PPHomeNavigationController *navigationController = [[PPHomeNavigationController alloc] initWithRootViewController:homeViewController];
                                [[[UIApplication sharedApplication] delegate] window].rootViewController = navigationController;
                            } else {
                                [strongSelf.navigationController popToRootViewControllerAnimated:YES];
                            }
                        }];
                    }];

                } else {
                    [strongSelf.navigationController.view toastMessage:error.networkPrompt];
                }
            }];

        } else {
            [hud hide:YES];

            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
        }
    }];

}

#pragma mark - UITextFieldDelegate

- (BOOL)checkoutText:(UITextField *)textField{
    for (UIView *v in self.view.subviews) {
        if ([v isKindOfClass:[UITextField class]] && v!=textField) {
            UITextField *f = (UITextField *)v;
            if (f.text.length <= 0) {
                return NO;
            }
        }
    }
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    if (textField.text.length <= 1 && string.length<=0) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    }else{
        self.navigationItem.rightBarButtonItem.enabled = [self checkoutText:textField];
    }
    
    if([string isEqualToString:@"\n"]) {
        if(textField == _phontField) {
            [_codeField becomeFirstResponder];
        } else if(textField == _codeField) {
            [_passwordField becomeFirstResponder];
        } else {
            [_passwordField resignFirstResponder];
        }

        return NO;
    }

    NSString *phone = _phontField.text;
    NSString *code = _codeField.text;
    NSString *password = _passwordField.text;

    if(textField == _phontField) {
        phone = [phone stringByReplacingCharactersInRange:range withString:string];
    } else if(textField == _codeField) {
        code = [code stringByReplacingCharactersInRange:range withString:string];
    } else {
        password = [password stringByReplacingCharactersInRange:range withString:string];
    }

    if(phone.length > 11 || code.length > 8) {
        return NO;
    }

    _retrieveButton.enabled = (phone.length > 0 && code.length > 0 && password.length > 0);

    return YES;
}

@end
